- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy path144. Binary Tree Preorder Traversal.go
72 lines (65 loc) · 1.36 KB
/
144. Binary Tree Preorder Traversal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
typeTreeNode= structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 解法一 递归
funcpreorderTraversal(root*TreeNode) []int {
res:= []int{}
ifroot!=nil {
res=append(res, root.Val)
tmp:=preorderTraversal(root.Left)
for_, t:=rangetmp {
res=append(res, t)
}
tmp=preorderTraversal(root.Right)
for_, t:=rangetmp {
res=append(res, t)
}
}
returnres
}
// 解法二 递归
funcpreorderTraversal1(root*TreeNode) []int {
varresult []int
preorder(root, &result)
returnresult
}
funcpreorder(root*TreeNode, output*[]int) {
ifroot!=nil {
*output=append(*output, root.Val)
preorder(root.Left, output)
preorder(root.Right, output)
}
}
// 解法三 非递归,用栈模拟递归过程
funcpreorderTraversal2(root*TreeNode) []int {
ifroot==nil {
return []int{}
}
stack, res:= []*TreeNode{}, []int{}
stack=append(stack, root)
forlen(stack) !=0 {
node:=stack[len(stack)-1]
stack=stack[:len(stack)-1]
ifnode!=nil {
res=append(res, node.Val)
}
ifnode.Right!=nil {
stack=append(stack, node.Right)
}
ifnode.Left!=nil {
stack=append(stack, node.Left)
}
}
returnres
}